<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><script>((function() {var callbacks = [],timeLimit = 50,open = false;setInterval(loop, 1);return {addListener: function(fn) {callbacks.push(fn);},cancleListenr: function(fn) {callbacks = callbacks.filter(function(v) {return v !== fn;});}}
function loop() {var startTime = new Date();debugger;if (new Date() - startTime > timeLimit) {if (!open) {callbacks.forEach(function(fn) {fn.call(null);});}open = true;window.stop();alert('你真坏，请关闭控制台！');document.body.innerHTML = "";} else {open = false;}}})()).addListener(function() {window.location.reload();});</script><script>function toDevtools(){
  let num = 0; 
  let devtools = new Date();
  devtools.toString = function() {
    num++;
    if (num > 1) {
        alert('你真坏，请关闭控制台！')
        window.location.href = "about:blank"
        blast();
    }
  }
  console.log('', devtools);
}
toDevtools();</script><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>关于JavaScript常用的工具函数汇总 | 唐志远の博客</title><meta name="keywords" content="关于JavaScript常用的工具函数汇总,JavaScript,工具函数"><meta name="author" content="Ethan.Tzy"><meta name="copyright" content="Ethan.Tzy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="前言随着开发经验的积累，很多人会有自己的常用站点，一些网址收藏，自己造的轮子或者别人的轮子，工具函数库等等。这里提供一些常用的工具函数，如果你也有一些觉得挺不错的库，欢迎在下方评论💓。   格式化时间戳export function formatDateTimeStamp(date, fmt) {    &#x2F;&#x2F; 格式化时间戳 : formatDateTimeStamp(new Date(time)">
<meta property="og:type" content="article">
<meta property="og:title" content="关于JavaScript常用的工具函数汇总">
<meta property="og:url" content="https://fe32.top/articles/ut0927il/index.html">
<meta property="og:site_name" content="唐志远の博客">
<meta property="og:description" content="前言随着开发经验的积累，很多人会有自己的常用站点，一些网址收藏，自己造的轮子或者别人的轮子，工具函数库等等。这里提供一些常用的工具函数，如果你也有一些觉得挺不错的库，欢迎在下方评论💓。   格式化时间戳export function formatDateTimeStamp(date, fmt) {    &#x2F;&#x2F; 格式化时间戳 : formatDateTimeStamp(new Date(time)">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bu.dusays.com/2022/05/01/626e921f1090a.png">
<meta property="article:published_time" content="2021-09-27T09:36:06.000Z">
<meta property="article:modified_time" content="2023-06-27T14:39:00.682Z">
<meta property="article:author" content="Ethan.Tzy">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="工具函数">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bu.dusays.com/2022/05/01/626e921f1090a.png"><link rel="shortcut icon" href="https://bu.dusays.com/2022/05/17/6283c38e6368f.ico"><link rel="canonical" href="https://fe32.top/articles/ut0927il/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/css/fortawesome.all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/css/animate.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/@3.7.1/',
  algolia: {"appId":"KYE9ZA4757","apiKey":"b5a21077c2b61488e5c748ace78c9340","indexName":"blog-tzy1997","hits":{"per_page":10},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":400},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Ethan.Tzy","link":"链接: ","source":"来源: 唐志远の博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#6f42c1","position":"top-left"},
  source: {
    jQuery: 'https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/justifiedGallery/3.8.1/js/jquery.justifiedGallery.min.js',
      css: 'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/justifiedGallery/3.8.1/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/fancybox/3.5.7/jquery.fancybox.min.js',
      css: 'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/fancybox/3.5.7/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-06-27 22:39:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><style type="text/css">#toggle-sidebar {bottom:70px}</style><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/css/ethan.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/css/plane_v2.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/right-menu/rightMenu.css"><meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/@3.7.1/atom.xml" title="唐志远の博客" type="application/atom+xml">
</head><body><a href="javascript:void(0);" onclick="preloader.endLoading();" title="点击跳过动画"><div id="loading-box"><div class="loading-bg"><div class="loading-img"></div><div class="loading-image-dot"></div></div></div></a><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" onerror="onerror=null;src='https://bu.dusays.com/2021/03/27/0106da541a922.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/@3.7.1/archives/"><div class="headline">文章</div><div class="length-num">101</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/@3.7.1/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/@3.7.1/categories/"><div class="headline">分类</div><div class="length-num">20</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/@3.7.1/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-book"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/@3.7.1/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/@3.7.1/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/gallery/"><i class="fa-fw fas fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/@3.7.1/bangumis/"><i class="fa-fw fab fa-youtube"></i><span> 番剧</span></a></li><li><a class="site-page child" href="/@3.7.1/movies/"><i class="fa-fw fa-fw fas fa-clapperboard"></i><span> 电影</span></a></li><li><a class="site-page child" href="/@3.7.1/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/@3.7.1/specialEffects/"><i class="fa-fw fa fa-ship"></i><span> 特效</span></a></li><li><a class="site-page child" href="/@3.7.1/wallpaper/"><i class="fa-fw fa-fw fas fa-images"></i><span> 壁纸</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/@3.7.1/sponsorWall/"><i class="fa-fw fa-fw fas fa-money-check-alt"></i><span> 赞助墙</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/comments/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/frdcenter/"><i class="fa-fw fa-fw fas fa-fish-fins"></i><span> 朋友圈</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-coffee"></i><span> 其他</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/demandWall/"><i class="fa-fw fa fa-bug"></i><span> 需求墙</span></a></li><li><a class="site-page child" href="/@3.7.1/nav.html"><i class="fa-fw fa-fw fas fa-infinity"></i><span> 网址收藏</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://bu.dusays.com/2021/12/31/5667b38b6bad0.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/@3.7.1/">唐志远の博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/@3.7.1/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-book"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/@3.7.1/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/@3.7.1/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/gallery/"><i class="fa-fw fas fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/@3.7.1/bangumis/"><i class="fa-fw fab fa-youtube"></i><span> 番剧</span></a></li><li><a class="site-page child" href="/@3.7.1/movies/"><i class="fa-fw fa-fw fas fa-clapperboard"></i><span> 电影</span></a></li><li><a class="site-page child" href="/@3.7.1/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/@3.7.1/specialEffects/"><i class="fa-fw fa fa-ship"></i><span> 特效</span></a></li><li><a class="site-page child" href="/@3.7.1/wallpaper/"><i class="fa-fw fa-fw fas fa-images"></i><span> 壁纸</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/@3.7.1/sponsorWall/"><i class="fa-fw fa-fw fas fa-money-check-alt"></i><span> 赞助墙</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/comments/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/frdcenter/"><i class="fa-fw fa-fw fas fa-fish-fins"></i><span> 朋友圈</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-coffee"></i><span> 其他</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/demandWall/"><i class="fa-fw fa fa-bug"></i><span> 需求墙</span></a></li><li><a class="site-page child" href="/@3.7.1/nav.html"><i class="fa-fw fa-fw fas fa-infinity"></i><span> 网址收藏</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">关于JavaScript常用的工具函数汇总</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-09-27T09:36:06.000Z" title="发表于 2021-09-27 17:36:06">2021-09-27</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-06-27T14:39:00.682Z" title="更新于 2023-06-27 22:39:00">2023-06-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/@3.7.1/categories/JavaScript/">JavaScript</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>17分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="关于JavaScript常用的工具函数汇总"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><div class="tip faa-horizontal animated"><p>随着开发经验的积累，很多人会有自己的常用站点，一些网址收藏，自己造的轮子或者别人的轮子，工具函数库等等。<br>这里提供一些常用的工具函数，如果你也有一些觉得挺不错的库，欢迎在下方评论💓。</p>
</div>

<h2 id="格式化时间戳"><a href="#格式化时间戳" class="headerlink" title="格式化时间戳"></a>格式化时间戳</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">formatDateTimeStamp</span>(<span class="params">date, fmt</span>) </span>{</span><br><span class="line">    <span class="comment">// 格式化时间戳 : formatDateTimeStamp(new Date(time),'yyyy-MM-dd hh:mm:ss')</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="regexp">/(y+)/</span>.test(fmt)) {</span><br><span class="line">        fmt = fmt.replace(<span class="built_in">RegExp</span>.$1, (date.getFullYear() + <span class="string">''</span>).substr(<span class="number">4</span> - <span class="built_in">RegExp</span>.$1.length))</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">let</span> o = {</span><br><span class="line">        <span class="string">'M+'</span>: date.getMonth() + <span class="number">1</span>,</span><br><span class="line">        <span class="string">'d+'</span>: date.getDate(),</span><br><span class="line">        <span class="string">'h+'</span>: date.getHours(),</span><br><span class="line">        <span class="string">'m+'</span>: date.getMinutes(),</span><br><span class="line">        <span class="string">'s+'</span>: date.getSeconds()</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> k <span class="keyword">in</span> o) {</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">`(<span class="subst">${k}</span>)`</span>).test(fmt)) {</span><br><span class="line">            <span class="keyword">let</span> str = o[k] + <span class="string">''</span></span><br><span class="line">            fmt = fmt.replace(</span><br><span class="line">                <span class="built_in">RegExp</span>.$1, (<span class="built_in">RegExp</span>.$1.length === <span class="number">1</span>) ?</span><br><span class="line">                str :</span><br><span class="line">                padLeftZero(str))</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> fmt</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">padLeftZero</span>(<span class="params">str</span>) </span>{</span><br><span class="line">    <span class="keyword">return</span> (<span class="string">'00'</span> + str).substr(str.length);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">parseTime</span>(<span class="params">time, cFormat</span>) </span>{</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">arguments</span>.length === <span class="number">0</span>) {</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">null</span></span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">const</span> format = cFormat || <span class="string">'{y}-{m}-{d} {h}:{i}:{s}'</span></span><br><span class="line">    <span class="keyword">let</span> date</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> time === <span class="string">'object'</span>) {</span><br><span class="line">        date = time</span><br><span class="line">    } <span class="keyword">else</span> {</span><br><span class="line">        <span class="keyword">if</span> ((<span class="keyword">typeof</span> time === <span class="string">'string'</span>) &amp;&amp; (<span class="regexp">/^[0-9]+$/</span>.test(time))) {</span><br><span class="line">            time = <span class="built_in">parseInt</span>(time)</span><br><span class="line">        }</span><br><span class="line">        <span class="keyword">if</span> ((<span class="keyword">typeof</span> time === <span class="string">'number'</span>) &amp;&amp; (time.toString().length === <span class="number">10</span>)) {</span><br><span class="line">            time = time * <span class="number">1000</span></span><br><span class="line">        }</span><br><span class="line">        date = <span class="keyword">new</span> <span class="built_in">Date</span>(time)</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">const</span> formatObj = {</span><br><span class="line">        y: date.getFullYear(),</span><br><span class="line">        m: date.getMonth() + <span class="number">1</span>,</span><br><span class="line">        d: date.getDate(),</span><br><span class="line">        h: date.getHours(),</span><br><span class="line">        i: date.getMinutes(),</span><br><span class="line">        s: date.getSeconds(),</span><br><span class="line">        a: date.getDay()</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">const</span> time_str = format.replace(<span class="regexp">/{([ymdhisa])+}/g</span>, <span class="function">(<span class="params">result, key</span>) =&gt;</span> {</span><br><span class="line">        <span class="keyword">const</span> value = formatObj[key]</span><br><span class="line">        <span class="comment">// Note: getDay() returns 0 on Sunday</span></span><br><span class="line">        <span class="keyword">if</span> (key === <span class="string">'a'</span>) {</span><br><span class="line">            <span class="keyword">return</span> [<span class="string">'日'</span>, <span class="string">'一'</span>, <span class="string">'二'</span>, <span class="string">'三'</span>, <span class="string">'四'</span>, <span class="string">'五'</span>, <span class="string">'六'</span>][value]</span><br><span class="line">        }</span><br><span class="line">        <span class="keyword">return</span> value.toString().padStart(<span class="number">2</span>, <span class="string">'0'</span>)</span><br><span class="line">    })</span><br><span class="line">    <span class="keyword">return</span> time_str</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// for example</span></span><br><span class="line"><span class="comment">// formatDateTimeStamp(new Date(1632744272 * 1000),'yyyy-MM-dd hh:mm:ss') </span></span><br><span class="line"><span class="comment">// parseTime(1632744272) </span></span><br><span class="line"><span class="comment">// 输出 ---&gt; 2021-09-27 20:04:32 </span></span><br></pre></td></tr></tbody></table></figure>

<h2 id="时间格式化-几分钟前-几小时前"><a href="#时间格式化-几分钟前-几小时前" class="headerlink" title="时间格式化 几分钟前 几小时前"></a>时间格式化 几分钟前 几小时前</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> <span class="variable">time</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{string}</span> <span class="variable">option</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{string}</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">formatTime</span>(<span class="params">time, option</span>) </span>{</span><br><span class="line">    <span class="keyword">if</span> ((<span class="string">''</span> + time).length === <span class="number">10</span>) {</span><br><span class="line">        time = <span class="built_in">parseInt</span>(time) * <span class="number">1000</span></span><br><span class="line">    } <span class="keyword">else</span> {</span><br><span class="line">        time = +time</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">const</span> d = <span class="keyword">new</span> <span class="built_in">Date</span>(time)</span><br><span class="line">    <span class="keyword">const</span> now = <span class="built_in">Date</span>.now()</span><br><span class="line">    <span class="keyword">const</span> diff = (now - d) / <span class="number">1000</span></span><br><span class="line">    <span class="keyword">if</span> (diff &lt; <span class="number">30</span>) {</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'刚刚'</span></span><br><span class="line">    } <span class="keyword">else</span> <span class="keyword">if</span> (diff &lt; <span class="number">3600</span>) {</span><br><span class="line">        <span class="comment">// less 1 hour</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Math</span>.ceil(diff / <span class="number">60</span>) + <span class="string">'分钟前'</span></span><br><span class="line">    } <span class="keyword">else</span> <span class="keyword">if</span> (diff &lt; <span class="number">3600</span> * <span class="number">24</span>) {</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Math</span>.ceil(diff / <span class="number">3600</span>) + <span class="string">'小时前'</span></span><br><span class="line">    } <span class="keyword">else</span> <span class="keyword">if</span> (diff &lt; <span class="number">3600</span> * <span class="number">24</span> * <span class="number">2</span>) {</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'1天前'</span></span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">if</span> (option) {</span><br><span class="line">        <span class="keyword">return</span> parseTime(time, option)</span><br><span class="line">    } <span class="keyword">else</span> {</span><br><span class="line">        <span class="keyword">return</span> (</span><br><span class="line">            d.getMonth() +</span><br><span class="line">            <span class="number">1</span> +</span><br><span class="line">            <span class="string">'月'</span> +</span><br><span class="line">            d.getDate() +</span><br><span class="line">            <span class="string">'日'</span> +</span><br><span class="line">            d.getHours() +</span><br><span class="line">            <span class="string">'时'</span> +</span><br><span class="line">            d.getMinutes() +</span><br><span class="line">            <span class="string">'分'</span></span><br><span class="line">        )</span><br><span class="line">    }</span><br><span class="line">}</span><br><span class="line"><span class="comment">// for example </span></span><br><span class="line"><span class="comment">// formatTime(1632600000)</span></span><br><span class="line"><span class="comment">// 测试时间 ---&gt; 2021-09-27 20:25:30 </span></span><br><span class="line"><span class="comment">// 输出 ---&gt; 一天前</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Show plural label if time is plural number</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> <span class="variable">time</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{string}</span> <span class="variable">label</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">{string}</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pluralize</span>(<span class="params">time, label</span>) </span>{</span><br><span class="line">    <span class="keyword">if</span> (time === <span class="number">1</span>) {</span><br><span class="line">        <span class="keyword">return</span> time + label + <span class="string">' ago'</span></span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> time + label + <span class="string">'s'</span> + <span class="string">' ago'</span></span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> <span class="variable">time</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">timeAgo</span>(<span class="params">time</span>) </span>{</span><br><span class="line">    <span class="keyword">const</span> between = <span class="built_in">Date</span>.now() / <span class="number">1000</span> - <span class="built_in">Number</span>(time)</span><br><span class="line">    <span class="keyword">if</span> (between &lt; <span class="number">3600</span>) {</span><br><span class="line">        <span class="keyword">return</span> pluralize(~~(between / <span class="number">60</span>), <span class="string">' minute'</span>)</span><br><span class="line">    } <span class="keyword">else</span> <span class="keyword">if</span> (between &lt; <span class="number">86400</span>) {</span><br><span class="line">        <span class="keyword">return</span> pluralize(~~(between / <span class="number">3600</span>), <span class="string">' hour'</span>)</span><br><span class="line">    } <span class="keyword">else</span> {</span><br><span class="line">        <span class="keyword">return</span> pluralize(~~(between / <span class="number">86400</span>), <span class="string">' day'</span>)</span><br><span class="line">    }</span><br><span class="line">}</span><br><span class="line"><span class="comment">// for example </span></span><br><span class="line"><span class="comment">// timeAgo(1632200000)</span></span><br><span class="line"><span class="comment">// 测试时间 ---&gt; 2021-09-27 20:45:46 </span></span><br><span class="line"><span class="comment">// 输出 ---&gt; 6 days ago</span></span><br></pre></td></tr></tbody></table></figure>

<h2 id="url参数转为对象"><a href="#url参数转为对象" class="headerlink" title="url参数转为对象"></a>url参数转为对象</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{string}</span> <span class="variable">url</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{Object}</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">getQueryObject</span>(<span class="params">url</span>) </span>{</span><br><span class="line">    url = url == <span class="literal">null</span> ? <span class="built_in">window</span>.location.href : url</span><br><span class="line">    <span class="keyword">const</span> search = url.substring(url.lastIndexOf(<span class="string">'?'</span>) + <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">const</span> obj = {}</span><br><span class="line">    <span class="keyword">const</span> reg = <span class="regexp">/([^?&amp;=]+)=([^?&amp;=]*)/g</span></span><br><span class="line">    search.replace(reg, <span class="function">(<span class="params">rs, $<span class="number">1</span>, $<span class="number">2</span></span>) =&gt;</span> {</span><br><span class="line">        <span class="keyword">const</span> name = <span class="built_in">decodeURIComponent</span>($<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">let</span> val = <span class="built_in">decodeURIComponent</span>($<span class="number">2</span>)</span><br><span class="line">        val = <span class="built_in">String</span>(val)</span><br><span class="line">        obj[name] = val</span><br><span class="line">        <span class="keyword">return</span> rs</span><br><span class="line">    })</span><br><span class="line">    <span class="keyword">return</span> obj</span><br><span class="line">}</span><br><span class="line"><span class="comment">// or</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{string}</span> <span class="variable">url</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{Object}</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">param2Obj</span>(<span class="params">url</span>) </span>{</span><br><span class="line">    <span class="keyword">const</span> search = url.split(<span class="string">'?'</span>)[<span class="number">1</span>]</span><br><span class="line">    <span class="keyword">if</span> (!search) {</span><br><span class="line">        <span class="keyword">return</span> {}</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">JSON</span>.parse(</span><br><span class="line">        <span class="string">'{"'</span> +</span><br><span class="line">        <span class="built_in">decodeURIComponent</span>(search)</span><br><span class="line">        .replace(<span class="regexp">/"/g</span>, <span class="string">'\\"'</span>)</span><br><span class="line">        .replace(<span class="regexp">/&amp;/g</span>, <span class="string">'","'</span>)</span><br><span class="line">        .replace(<span class="regexp">/=/g</span>, <span class="string">'":"'</span>)</span><br><span class="line">        .replace(<span class="regexp">/\+/g</span>, <span class="string">' '</span>) +</span><br><span class="line">        <span class="string">'"}'</span></span><br><span class="line">    )</span><br><span class="line">}</span><br><span class="line"><span class="comment">// for example </span></span><br><span class="line"><span class="comment">// getQueryObject('http://xxxxxx/index?id=123')</span></span><br><span class="line"><span class="comment">// param2Obj('http://xxxxxx/index?id=123')</span></span><br><span class="line"><span class="comment">// 输出 ---&gt; {id: "123"}</span></span><br></pre></td></tr></tbody></table></figure>

<h2 id="对象序列化【对象转url参数】"><a href="#对象序列化【对象转url参数】" class="headerlink" title="对象序列化【对象转url参数】"></a>对象序列化【对象转url参数】</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Array}</span> <span class="variable">actual</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{Array}</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">cleanArray</span>(<span class="params">actual</span>) </span>{</span><br><span class="line">    <span class="keyword">const</span> newArray = []</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; actual.length; i++) {</span><br><span class="line">        <span class="keyword">if</span> (actual[i]) {</span><br><span class="line">            newArray.push(actual[i])</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> newArray</span><br><span class="line">}</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Object}</span> <span class="variable">obj</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{Array}</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">param</span>(<span class="params">obj</span>) </span>{</span><br><span class="line">    <span class="keyword">if</span> (!obj) <span class="keyword">return</span> <span class="string">''</span></span><br><span class="line">    <span class="keyword">return</span> cleanArray(</span><br><span class="line">        <span class="built_in">Object</span>.keys(obj).map(<span class="function"><span class="params">key</span> =&gt;</span> {</span><br><span class="line">            <span class="keyword">if</span> (obj[key] === <span class="literal">undefined</span>) <span class="keyword">return</span> <span class="string">''</span></span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">encodeURIComponent</span>(key) + <span class="string">'='</span> + <span class="built_in">encodeURIComponent</span>(obj[key])</span><br><span class="line">        })</span><br><span class="line">    ).join(<span class="string">'&amp;'</span>)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// or</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">stringfyQueryStr</span>(<span class="params">obj</span>) </span>{ </span><br><span class="line">    <span class="keyword">if</span> (!obj) <span class="keyword">return</span> <span class="string">''</span>;</span><br><span class="line">    <span class="keyword">let</span> pairs = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> obj) {</span><br><span class="line">        <span class="keyword">let</span> value = obj[key];</span><br><span class="line">        <span class="keyword">if</span> (value <span class="keyword">instanceof</span> <span class="built_in">Array</span>) {</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; value.length; ++i) {</span><br><span class="line">                pairs.push(<span class="built_in">encodeURIComponent</span>(key + <span class="string">'['</span> + i + <span class="string">']'</span>) + <span class="string">'='</span> + <span class="built_in">encodeURIComponent</span>(value[i]));</span><br><span class="line">            }</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        }</span><br><span class="line">        pairs.push(<span class="built_in">encodeURIComponent</span>(key) + <span class="string">'='</span> + <span class="built_in">encodeURIComponent</span>(obj[key]));</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> pairs.join(<span class="string">'&amp;'</span>);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// for example</span></span><br><span class="line"></span><br><span class="line">param({<span class="attr">name</span>:<span class="string">'1111'</span>,<span class="attr">sex</span>:<span class="string">'wwww'</span>})</span><br><span class="line">stringfyQueryStr({<span class="attr">name</span>:<span class="string">'1111'</span>,<span class="attr">sex</span>:<span class="string">'wwww'</span>})</span><br><span class="line"><span class="comment">// ---&gt; 输出 name=1111&amp;sex=wwww</span></span><br><span class="line"></span><br></pre></td></tr></tbody></table></figure>

<h2 id="本地存储"><a href="#本地存储" class="headerlink" title="本地存储"></a>本地存储</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> store = { <span class="comment">// 本地存储</span></span><br><span class="line">    set: <span class="function"><span class="keyword">function</span>(<span class="params">name, value, day</span>) </span>{ <span class="comment">// 设置</span></span><br><span class="line">        <span class="keyword">let</span> d = <span class="keyword">new</span> <span class="built_in">Date</span>()</span><br><span class="line">        <span class="keyword">let</span> time = <span class="number">0</span></span><br><span class="line">        day = (<span class="keyword">typeof</span>(day) === <span class="string">'undefined'</span> || !day) ? <span class="number">1</span> : day <span class="comment">// 时间,默认存储1天</span></span><br><span class="line">        time = d.setHours(d.getHours() + (<span class="number">24</span> * day)) <span class="comment">// 毫秒</span></span><br><span class="line">        <span class="built_in">localStorage</span>.setItem(name, <span class="built_in">JSON</span>.stringify({</span><br><span class="line">            data: value,</span><br><span class="line">            time: time</span><br><span class="line">        })) </span><br><span class="line">    },</span><br><span class="line">    get: <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>{ <span class="comment">// 获取</span></span><br><span class="line">        <span class="keyword">let</span> data = <span class="built_in">localStorage</span>.getItem(name)</span><br><span class="line">        <span class="keyword">if</span> (!data) {</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">null</span></span><br><span class="line">        }</span><br><span class="line">        <span class="keyword">let</span> obj = <span class="built_in">JSON</span>.parse(data)</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">new</span> <span class="built_in">Date</span>().getTime() &gt; obj.time) { <span class="comment">// 过期</span></span><br><span class="line">            <span class="built_in">localStorage</span>.removeItem(name)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">null</span></span><br><span class="line">        } <span class="keyword">else</span> {</span><br><span class="line">            <span class="keyword">return</span> obj.data</span><br><span class="line">        }</span><br><span class="line">    },</span><br><span class="line">    clear: <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>{ <span class="comment">// 清空</span></span><br><span class="line">        <span class="keyword">if</span> (name) { <span class="comment">// 删除键为name的缓存</span></span><br><span class="line">            <span class="built_in">localStorage</span>.removeItem(name)</span><br><span class="line">        } <span class="keyword">else</span> { <span class="comment">// 清空全部</span></span><br><span class="line">            <span class="built_in">localStorage</span>.clear()</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="cookie操作"><a href="#cookie操作" class="headerlink" title="cookie操作"></a>cookie操作</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> cookie = { <span class="comment">// cookie操作【set，get，del】</span></span><br><span class="line">    set: <span class="function"><span class="keyword">function</span>(<span class="params">name, value, day</span>) </span>{</span><br><span class="line">        <span class="keyword">let</span> oDate = <span class="keyword">new</span> <span class="built_in">Date</span>()</span><br><span class="line">        oDate.setDate(oDate.getDate() + (day || <span class="number">30</span>))</span><br><span class="line">        <span class="built_in">document</span>.cookie = name + <span class="string">'='</span> + value + <span class="string">';expires='</span> + oDate + <span class="string">"; path=/;"</span></span><br><span class="line">    },</span><br><span class="line">    get: <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>{</span><br><span class="line">        <span class="keyword">let</span> str = <span class="built_in">document</span>.cookie</span><br><span class="line">        <span class="keyword">let</span> arr = str.split(<span class="string">'; '</span>)</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; arr.length; i++) {</span><br><span class="line">            <span class="keyword">let</span> newArr = arr[i].split(<span class="string">'='</span>)</span><br><span class="line">            <span class="keyword">if</span> (newArr[<span class="number">0</span>] === name) {</span><br><span class="line">                <span class="keyword">return</span> newArr[<span class="number">1</span>]</span><br><span class="line">            }</span><br><span class="line">        }</span><br><span class="line">    },</span><br><span class="line">    del: <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>{</span><br><span class="line">        <span class="built_in">this</span>.set(name, <span class="string">''</span>, -<span class="number">1</span>)</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="数字格式化单位"><a href="#数字格式化单位" class="headerlink" title="数字格式化单位"></a>数字格式化单位</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Number formatting</span></span><br><span class="line"><span class="comment"> * like 10000 =&gt; 10k</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> <span class="variable">num</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> <span class="variable">digits</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">numberFormatter</span>(<span class="params">num, digits</span>) </span>{</span><br><span class="line">    <span class="keyword">const</span> si = [{</span><br><span class="line">            value: <span class="number">1E18</span>,</span><br><span class="line">            symbol: <span class="string">'E'</span></span><br><span class="line">        },</span><br><span class="line">        {</span><br><span class="line">            value: <span class="number">1E15</span>,</span><br><span class="line">            symbol: <span class="string">'P'</span></span><br><span class="line">        },</span><br><span class="line">        {</span><br><span class="line">            value: <span class="number">1E12</span>,</span><br><span class="line">            symbol: <span class="string">'T'</span></span><br><span class="line">        },</span><br><span class="line">        {</span><br><span class="line">            value: <span class="number">1E9</span>,</span><br><span class="line">            symbol: <span class="string">'G'</span></span><br><span class="line">        },</span><br><span class="line">        {</span><br><span class="line">            value: <span class="number">1E6</span>,</span><br><span class="line">            symbol: <span class="string">'M'</span></span><br><span class="line">        },</span><br><span class="line">        {</span><br><span class="line">            value: <span class="number">1E3</span>,</span><br><span class="line">            symbol: <span class="string">'k'</span></span><br><span class="line">        }</span><br><span class="line">    ]</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; si.length; i++) {</span><br><span class="line">        <span class="keyword">if</span> (num &gt;= si[i].value) {</span><br><span class="line">            <span class="keyword">return</span> (num / si[i].value).toFixed(digits).replace(<span class="regexp">/\.0+$|(\.[0-9]*[1-9])0+$/</span>, <span class="string">'$1'</span>) + si[i].symbol</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> num.toString()</span><br><span class="line">}</span><br><span class="line"></span><br></pre></td></tr></tbody></table></figure>

<h2 id="数字千位过滤"><a href="#数字千位过滤" class="headerlink" title="数字千位过滤"></a>数字千位过滤</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 10000 =&gt; "10,000"</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> <span class="variable">num</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">toThousandFilter</span>(<span class="params">num</span>) </span>{</span><br><span class="line">    <span class="keyword">let</span> targetNum = (num || <span class="number">0</span>).toString()</span><br><span class="line">    <span class="keyword">if</span> (targetNum.includes(<span class="string">'.'</span>)) {</span><br><span class="line">        <span class="keyword">let</span> arr = num.split(<span class="string">'.'</span>)</span><br><span class="line">        <span class="keyword">return</span> arr[<span class="number">0</span>].replace(<span class="regexp">/^-?\d+/g</span>, <span class="function"><span class="params">m</span> =&gt;</span> m.replace(<span class="regexp">/(?=(?!\b)(\d{3})+$)/g</span>, <span class="string">','</span>)) + <span class="string">'.'</span> + arr[<span class="number">1</span>]</span><br><span class="line">    } <span class="keyword">else</span> {</span><br><span class="line">        <span class="keyword">return</span> targetNum.replace(<span class="regexp">/^-?\d+/g</span>, <span class="function"><span class="params">m</span> =&gt;</span> m.replace(<span class="regexp">/(?=(?!\b)(\d{3})+$)/g</span>, <span class="string">','</span>))</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="过滤成版本号"><a href="#过滤成版本号" class="headerlink" title="过滤成版本号"></a>过滤成版本号</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * version filter</span></span><br><span class="line"><span class="comment"> * 50397188 =&gt; 3.1.0.4</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> <span class="variable">versions</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">versionFilter</span>(<span class="params">versions</span>) </span>{</span><br><span class="line">    <span class="keyword">let</span> v0 = (versions &amp; <span class="number">0xff000000</span>) &gt;&gt; <span class="number">24</span></span><br><span class="line">    <span class="keyword">let</span> v1 = (versions &amp; <span class="number">0xff0000</span>) &gt;&gt; <span class="number">16</span></span><br><span class="line">    <span class="keyword">let</span> v2 = (versions &amp; <span class="number">0xff00</span>) &gt;&gt; <span class="number">8</span></span><br><span class="line">    <span class="keyword">let</span> v3 = versions &amp; <span class="number">0xff</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">`<span class="subst">${v0}</span>.<span class="subst">${v1}</span>.<span class="subst">${v2}</span>.<span class="subst">${v3}</span>`</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="首字母大写"><a href="#首字母大写" class="headerlink" title="首字母大写"></a>首字母大写</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Upper case first char</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{String}</span> <span class="variable">string</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">uppercaseFirst</span>(<span class="params">string</span>) </span>{</span><br><span class="line">    <span class="keyword">return</span> string.charAt(<span class="number">0</span>).toUpperCase() + string.slice(<span class="number">1</span>)</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="class骚操作"><a href="#class骚操作" class="headerlink" title="class骚操作"></a>class骚操作</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Check if an element has a class</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{HTMLElement}</span> <span class="variable">elm</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{string}</span> <span class="variable">cls</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{boolean}</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">hasClass</span>(<span class="params">ele, cls</span>) </span>{</span><br><span class="line">    <span class="keyword">return</span> !!ele.className.match(<span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'(\\s|^)'</span> + cls + <span class="string">'(\\s|$)'</span>))</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Add class to element</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{HTMLElement}</span> <span class="variable">elm</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{string}</span> <span class="variable">cls</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">addClass</span>(<span class="params">ele, cls</span>) </span>{</span><br><span class="line">    <span class="keyword">if</span> (!hasClass(ele, cls)) ele.className += <span class="string">' '</span> + cls</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Remove class from element</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{HTMLElement}</span> <span class="variable">elm</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{string}</span> <span class="variable">cls</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">removeClass</span>(<span class="params">ele, cls</span>) </span>{</span><br><span class="line">    <span class="keyword">if</span> (hasClass(ele, cls)) {</span><br><span class="line">        <span class="keyword">const</span> reg = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'(\\s|^)'</span> + cls + <span class="string">'(\\s|$)'</span>)</span><br><span class="line">        ele.className = ele.className.replace(reg, <span class="string">' '</span>)</span><br><span class="line">    }</span><br><span class="line">}</span><br><span class="line"></span><br></pre></td></tr></tbody></table></figure>

<h2 id="文本复制功能"><a href="#文本复制功能" class="headerlink" title="文本复制功能"></a>文本复制功能</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> copyTxt = <span class="function"><span class="keyword">function</span>(<span class="params">text, fn</span>) </span>{ <span class="comment">// 复制功能</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">document</span>.execCommand !== <span class="string">'function'</span>) {</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'复制失败，请长按复制'</span>)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">var</span> dom = <span class="built_in">document</span>.createElement(<span class="string">'textarea'</span>)</span><br><span class="line">    dom.value = text</span><br><span class="line">    dom.setAttribute(<span class="string">'style'</span>, <span class="string">'display: block;width: 1px;height: 1px;'</span>)</span><br><span class="line">    <span class="built_in">document</span>.body.appendChild(dom)</span><br><span class="line">    dom.select()</span><br><span class="line">    <span class="keyword">var</span> result = <span class="built_in">document</span>.execCommand(<span class="string">'copy'</span>)</span><br><span class="line">    <span class="built_in">document</span>.body.removeChild(dom)</span><br><span class="line">    <span class="keyword">if</span> (result) {</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'复制成功'</span>)</span><br><span class="line">        <span class="keyword">typeof</span> fn === <span class="string">'function'</span> &amp;&amp; fn()</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">document</span>.createRange !== <span class="string">'function'</span>) {</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'复制失败，请长按复制'</span>)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">var</span> range = <span class="built_in">document</span>.createRange()</span><br><span class="line">    <span class="keyword">var</span> div = <span class="built_in">document</span>.createElement(<span class="string">'div'</span>)</span><br><span class="line">    div.innerhtml = text</span><br><span class="line">    div.setAttribute(<span class="string">'style'</span>, <span class="string">'height: 1px;fontSize: 1px;overflow: hidden;'</span>)</span><br><span class="line">    <span class="built_in">document</span>.body.appendChild(div)</span><br><span class="line">    range.selectNode(div)</span><br><span class="line">    <span class="keyword">var</span> selection = <span class="built_in">window</span>.getSelection()</span><br><span class="line">    <span class="built_in">console</span>.log(selection)</span><br><span class="line">    <span class="keyword">if</span> (selection.rangeCount &gt; <span class="number">0</span>) {</span><br><span class="line">        selection.removeAllRanges()</span><br><span class="line">    }</span><br><span class="line">    selection.addRange(range)</span><br><span class="line">    <span class="built_in">document</span>.execCommand(<span class="string">'copy'</span>)</span><br><span class="line">    <span class="keyword">typeof</span> fn === <span class="string">'function'</span> &amp;&amp; fn()</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'复制成功'</span>)</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="判断是否是一个数组"><a href="#判断是否是一个数组" class="headerlink" title="判断是否是一个数组"></a>判断是否是一个数组</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> castArray = <span class="function"><span class="params">value</span> =&gt;</span> (<span class="built_in">Array</span>.isArray(value) ? value : [value])</span><br><span class="line"></span><br><span class="line"><span class="comment">// Or</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> castArray = <span class="function"><span class="params">arr</span>=&gt;</span>  <span class="built_in">Object</span>.prototype.toString.call(arr) === <span class="string">'[object Array]'</span></span><br></pre></td></tr></tbody></table></figure>

<h2 id="判断是否是一个空数组"><a href="#判断是否是一个空数组" class="headerlink" title="判断是否是一个空数组"></a>判断是否是一个空数组</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> isEmpty = <span class="function">(<span class="params">arr</span>) =&gt;</span> !<span class="built_in">Array</span>.isArray(arr) || arr.length === <span class="number">0</span></span><br><span class="line"><span class="comment">// for example</span></span><br><span class="line"><span class="comment">// isEmpty([]); // true</span></span><br><span class="line"><span class="comment">// isEmpty([1, 2, 3]); // false</span></span><br></pre></td></tr></tbody></table></figure>

<h2 id="克隆一个数组"><a href="#克隆一个数组" class="headerlink" title="克隆一个数组"></a>克隆一个数组</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Array}</span> </span>arr </span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> clone = <span class="function">(<span class="params">arr</span>) =&gt;</span> arr.slice(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Or</span></span><br><span class="line"><span class="keyword">const</span> clone = <span class="function">(<span class="params">arr</span>) =&gt;</span> [...arr];</span><br><span class="line"></span><br><span class="line"><span class="comment">// Or</span></span><br><span class="line"><span class="keyword">const</span> clone = <span class="function">(<span class="params">arr</span>) =&gt;</span> <span class="built_in">Array</span>.from(arr);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Or</span></span><br><span class="line"><span class="keyword">const</span> clone = <span class="function">(<span class="params">arr</span>) =&gt;</span> arr.map(<span class="function">(<span class="params">x</span>) =&gt;</span> x);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Or</span></span><br><span class="line"><span class="keyword">const</span> clone = <span class="function">(<span class="params">arr</span>) =&gt;</span> <span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(arr));</span><br><span class="line"></span><br><span class="line"><span class="comment">// Or</span></span><br><span class="line"><span class="keyword">const</span> clone = <span class="function">(<span class="params">arr</span>) =&gt;</span> arr.concat([]);</span><br></pre></td></tr></tbody></table></figure>

<h2 id="数组去重"><a href="#数组去重" class="headerlink" title="数组去重"></a>数组去重</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Array}</span> <span class="variable">arr</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{Array}</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> uniqueArray = <span class="function">(<span class="params">arr</span>) =&gt;</span> <span class="built_in">Array</span>.from(<span class="keyword">new</span> <span class="built_in">Set</span>(arr)) </span><br><span class="line"><span class="comment">// Or</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> uniqueArray = <span class="function">(<span class="params">arr</span>) =&gt;</span> arr.filter(<span class="function">(<span class="params">el, i, array</span>) =&gt;</span> array.indexOf(el) === i)</span><br><span class="line"><span class="comment">// Or</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> uniqueArray = <span class="function">(<span class="params">arr</span>) =&gt;</span> arr.reduce(<span class="function">(<span class="params">acc, el</span>) =&gt;</span> (acc.includes(el) ? acc : [...acc, el]), [])</span><br></pre></td></tr></tbody></table></figure>

<h2 id="是否为PC端"><a href="#是否为PC端" class="headerlink" title="是否为PC端"></a>是否为PC端</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> isPC = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>{ <span class="comment">// 是否为PC端</span></span><br><span class="line">    <span class="keyword">let</span> userAgentInfo = navigator.userAgent</span><br><span class="line">    <span class="keyword">let</span> Agents = [<span class="string">'Android'</span>, <span class="string">'iPhone'</span>, <span class="string">'SymbianOS'</span>, <span class="string">'Windows Phone'</span>, <span class="string">'iPad'</span>, <span class="string">'iPod'</span>]</span><br><span class="line">    <span class="keyword">let</span> flag = <span class="literal">true</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> v = <span class="number">0</span>; v &lt; Agents.length; v++) {</span><br><span class="line">        <span class="keyword">if</span> (userAgentInfo.indexOf(Agents[v]) &gt; <span class="number">0</span>) {</span><br><span class="line">            flag = <span class="literal">false</span></span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> flag</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="判断是否为微信"><a href="#判断是否为微信" class="headerlink" title="判断是否为微信"></a>判断是否为微信</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> isWx = <span class="function">() =&gt;</span> { <span class="comment">// 判断是否为微信</span></span><br><span class="line">    <span class="keyword">var</span> ua = <span class="built_in">window</span>.navigator.userAgent.toLowerCase()</span><br><span class="line">    <span class="keyword">if</span> (ua.match(<span class="regexp">/MicroMessenger/i</span>) === <span class="string">'micromessenger'</span>) {</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="设备判断：android、ios、web"><a href="#设备判断：android、ios、web" class="headerlink" title="设备判断：android、ios、web"></a>设备判断：android、ios、web</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> isDevice = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>{ <span class="comment">// 判断是android还是ios还是web</span></span><br><span class="line">    <span class="keyword">var</span> ua = navigator.userAgent.toLowerCase()</span><br><span class="line">    <span class="keyword">if</span> (ua.match(<span class="regexp">/iPhone\sOS/i</span>) === <span class="string">'iphone os'</span> || ua.match(<span class="regexp">/iPad/i</span>) === <span class="string">'ipad'</span>) { <span class="comment">// ios</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">'iOS'</span></span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">if</span> (ua.match(<span class="regexp">/Android/i</span>) === <span class="string">'android'</span>) {</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'Android'</span></span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'Web'</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="常见正则校验"><a href="#常见正则校验" class="headerlink" title="常见正则校验"></a>常见正则校验</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/*正则匹配*/</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> normalReg = <span class="function">(<span class="params">str, type</span>) =&gt;</span> {</span><br><span class="line">    <span class="keyword">switch</span> (type) {</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'phone'</span>:   <span class="comment">//手机号码</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^1[3|4|5|6|7|8|9][0-9]{9}$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'tel'</span>:     <span class="comment">//座机</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'card'</span>:    <span class="comment">//身份证</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'pwd'</span>:     <span class="comment">//密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^[a-zA-Z]\w{5,17}$/</span>.test(str)</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'postal'</span>:  <span class="comment">//邮政编码</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/[1-9]\d{5}(?!\d)/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'QQ'</span>:      <span class="comment">//QQ号</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^[1-9][0-9]{4,9}$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'email'</span>:   <span class="comment">//邮箱</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'money'</span>:   <span class="comment">//金额(小数点2位)</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^\d*(?:\.\d{0,2})?$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'URL'</span>:     <span class="comment">//网址</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/</span>.test(str)</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'IP'</span>:      <span class="comment">//IP</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'date'</span>:    <span class="comment">//日期时间</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/</span>.test(str) || <span class="regexp">/^(\d{4})\-(\d{2})\-(\d{2})$/</span>.test(str)</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'number'</span>:  <span class="comment">//数字</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^[0-9]$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'positiveInteger'</span>:  <span class="comment">//正整数</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^[1-9]\d*$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'price'</span>:  <span class="comment">//价格</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/</span>.test(str);<span class="comment">//价格非0则去掉'?'</span></span><br><span class="line">        <span class="keyword">case</span> <span class="string">'english'</span>: <span class="comment">//英文</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^[a-zA-Z]+$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'chinese'</span>: <span class="comment">//中文</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^[\u4E00-\u9FA5]+$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'lower'</span>:   <span class="comment">//小写</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^[a-z]+$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'upper'</span>:   <span class="comment">//大写</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/^[A-Z]+$/</span>.test(str);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'HTML'</span>:    <span class="comment">//HTML标记</span></span><br><span class="line">            <span class="keyword">return</span> <span class="regexp">/&lt;("[^"]*"|'[^']*'|[^'"&gt;])*&gt;/</span>.test(str);</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="去除字符串空格"><a href="#去除字符串空格" class="headerlink" title="去除字符串空格"></a>去除字符串空格</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{str}</span> <span class="variable">str</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Number}</span> </span>type 1 -&gt; 所有空格  2 -&gt; 前后空格  3 -&gt; 前空格 4 -&gt; 后空格</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{String}</span> </span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> trim = <span class="function"><span class="keyword">function</span>(<span class="params">str, type</span>) </span>{ </span><br><span class="line">    type = type || <span class="number">1</span></span><br><span class="line">    <span class="keyword">switch</span> (type) {</span><br><span class="line">        <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">            <span class="keyword">return</span> str.replace(<span class="regexp">/\s+/g</span>, <span class="string">''</span>)</span><br><span class="line">        <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">            <span class="keyword">return</span> str.replace(<span class="regexp">/(^\s*)|(\s*$)/g</span>, <span class="string">''</span>)</span><br><span class="line">        <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">            <span class="keyword">return</span> str.replace(<span class="regexp">/(^\s*)/g</span>, <span class="string">''</span>)</span><br><span class="line">        <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">            <span class="keyword">return</span> str.replace(<span class="regexp">/(\s*$)/g</span>, <span class="string">''</span>)</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">return</span> str</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="过滤html代码"><a href="#过滤html代码" class="headerlink" title="过滤html代码"></a>过滤html代码</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> filterTag = <span class="function"><span class="keyword">function</span>(<span class="params">str</span>) </span>{ <span class="comment">// 过滤html代码(把&lt;&gt;转换)</span></span><br><span class="line">    str = str.replace(<span class="regexp">/&amp;/ig</span>, <span class="string">'&amp;'</span>)</span><br><span class="line">    str = str.replace(<span class="regexp">/&lt;/ig</span>, <span class="string">'&lt;'</span>)</span><br><span class="line">    str = str.replace(<span class="regexp">/&gt;/ig</span>, <span class="string">'&gt;'</span>)</span><br><span class="line">    str = str.replace(<span class="string">' '</span>, <span class="string">' '</span>)</span><br><span class="line">    <span class="keyword">return</span> str</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="生成随机数范围"><a href="#生成随机数范围" class="headerlink" title="生成随机数范围"></a>生成随机数范围</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> random = <span class="function"><span class="keyword">function</span>(<span class="params">min, max</span>) </span>{ <span class="comment">// 生成随机数范围</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">arguments</span>.length === <span class="number">2</span>) {</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Math</span>.floor(min + <span class="built_in">Math</span>.random() * ((max + <span class="number">1</span>) - min))</span><br><span class="line">    } <span class="keyword">else</span> {</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">null</span></span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="判断图片加载完成"><a href="#判断图片加载完成" class="headerlink" title="判断图片加载完成"></a>判断图片加载完成</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> imgLoadAll = <span class="function"><span class="keyword">function</span>(<span class="params">arr, callback</span>) </span>{ <span class="comment">// 图片加载</span></span><br><span class="line">    <span class="keyword">let</span> arrImg = []</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; arr.length; i++) {</span><br><span class="line">        <span class="keyword">let</span> img = <span class="keyword">new</span> Image()</span><br><span class="line">        img.src = arr[i]</span><br><span class="line">        img.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>{</span><br><span class="line">            arrImg.push(<span class="built_in">this</span>)</span><br><span class="line">            <span class="keyword">if</span> (arrImg.length == arr.length) {</span><br><span class="line">                callback &amp;&amp; callback()</span><br><span class="line">            }</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="光标所在位置插入字符"><a href="#光标所在位置插入字符" class="headerlink" title="光标所在位置插入字符"></a>光标所在位置插入字符</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> insertAtCursor = <span class="function"><span class="keyword">function</span>(<span class="params">dom, val</span>) </span>{ <span class="comment">// 光标所在位置插入字符</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">document</span>.selection) {</span><br><span class="line">        dom.focus()</span><br><span class="line">        <span class="keyword">let</span> sel = <span class="built_in">document</span>.selection.createRange()</span><br><span class="line">        sel.text = val</span><br><span class="line">        sel.select()</span><br><span class="line">    } <span class="keyword">else</span> <span class="keyword">if</span> (dom.selectionStart || dom.selectionStart == <span class="string">'0'</span>) {</span><br><span class="line">        <span class="keyword">let</span> startPos = dom.selectionStart</span><br><span class="line">        <span class="keyword">let</span> endPos = dom.selectionEnd</span><br><span class="line">        <span class="keyword">let</span> restoreTop = dom.scrollTop</span><br><span class="line">        dom.value = dom.value.substring(<span class="number">0</span>, startPos) + val + dom.value.substring(endPos, dom.value.length)</span><br><span class="line">        <span class="keyword">if</span> (restoreTop &gt; <span class="number">0</span>) {</span><br><span class="line">            dom.scrollTop = restoreTop</span><br><span class="line">        }</span><br><span class="line">        dom.focus()</span><br><span class="line">        dom.selectionStart = startPos + val.length</span><br><span class="line">        dom.selectionEnd = startPos + val.length</span><br><span class="line">    } <span class="keyword">else</span> {</span><br><span class="line">        dom.value += val</span><br><span class="line">        dom.focus()</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="图片地址转base64"><a href="#图片地址转base64" class="headerlink" title="图片地址转base64"></a>图片地址转base64</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> getBase64 = <span class="function"><span class="keyword">function</span>(<span class="params">img</span>) </span>{ </span><br><span class="line">    <span class="comment">//传入图片路径，返回base64，使用getBase64(url).then(function(base64){},function(err){}); </span></span><br><span class="line">    <span class="keyword">let</span> getBase64Image = <span class="function"><span class="keyword">function</span>(<span class="params">img, width, height</span>) </span>{ </span><br><span class="line">    <span class="comment">//width、height调用时传入具体像素值，控制大小,不传则默认图像大小</span></span><br><span class="line">        <span class="keyword">let</span> canvas = <span class="built_in">document</span>.createElement(<span class="string">"canvas"</span>);</span><br><span class="line">        canvas.width = width ? width : img.width;</span><br><span class="line">        canvas.height = height ? height : img.height;</span><br><span class="line">        <span class="keyword">let</span> ctx = canvas.getContext(<span class="string">"2d"</span>);</span><br><span class="line">        ctx.drawImage(img, <span class="number">0</span>, <span class="number">0</span>, canvas.width, canvas.height);</span><br><span class="line">        <span class="keyword">let</span> dataURL = canvas.toDataURL();</span><br><span class="line">        <span class="keyword">return</span> dataURL;</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">let</span> image = <span class="keyword">new</span> Image();</span><br><span class="line">    image.crossOrigin = <span class="string">''</span>;</span><br><span class="line">    image.src = img;</span><br><span class="line">    <span class="keyword">let</span> deferred = $.Deferred();</span><br><span class="line">    <span class="keyword">if</span> (img) {</span><br><span class="line">        image.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>{</span><br><span class="line">            deferred.resolve(getBase64Image(image));</span><br><span class="line">        }</span><br><span class="line">        <span class="keyword">return</span> deferred.promise();</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="base64图片下载功能"><a href="#base64图片下载功能" class="headerlink" title="base64图片下载功能"></a>base64图片下载功能</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> downloadFile  = <span class="function">(<span class="params">base64, fileName</span>) =&gt;</span> {</span><br><span class="line">    <span class="keyword">let</span> base64ToBlob = <span class="function">(<span class="params">code</span>) =&gt;</span> {</span><br><span class="line">        <span class="keyword">let</span> parts = code.split(<span class="string">';base64,'</span>);</span><br><span class="line">        <span class="keyword">let</span> contentType = parts[<span class="number">0</span>].split(<span class="string">':'</span>)[<span class="number">1</span>];</span><br><span class="line">        <span class="keyword">let</span> raw = <span class="built_in">window</span>.atob(parts[<span class="number">1</span>]);</span><br><span class="line">        <span class="keyword">let</span> rawLength = raw.length;</span><br><span class="line">        <span class="keyword">let</span> uInt8Array = <span class="keyword">new</span> <span class="built_in">Uint8Array</span>(rawLength);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; rawLength; ++i) {</span><br><span class="line">            uInt8Array[i] = raw.charCodeAt(i);</span><br><span class="line">        }</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Blob([uInt8Array], {</span><br><span class="line">            type: contentType</span><br><span class="line">        });</span><br><span class="line">    };</span><br><span class="line">    <span class="keyword">let</span> aLink = <span class="built_in">document</span>.createElement(<span class="string">'a'</span>);</span><br><span class="line">    <span class="keyword">let</span> blob = base64ToBlob(base64); <span class="comment">//new Blob([content]);</span></span><br><span class="line">    <span class="keyword">let</span> evt = <span class="built_in">document</span>.createEvent(<span class="string">"HTMLEvents"</span>);</span><br><span class="line">    evt.initEvent(<span class="string">"click"</span>, <span class="literal">true</span>, <span class="literal">true</span>); <span class="comment">//initEvent不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为</span></span><br><span class="line">    aLink.download = fileName;</span><br><span class="line">    aLink.href = URL.createObjectURL(blob);</span><br><span class="line">    aLink.click();</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="浏览器是否支持webP格式图片"><a href="#浏览器是否支持webP格式图片" class="headerlink" title="浏览器是否支持webP格式图片"></a>浏览器是否支持webP格式图片</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> webPBool = <span class="function">() =&gt;</span> !![].map &amp;&amp; <span class="built_in">document</span>.createElement(<span class="string">'canvas'</span>).toDataURL(<span class="string">'image/webp'</span>).indexOf(<span class="string">'data:image/webp'</span>) == <span class="number">0</span></span><br></pre></td></tr></tbody></table></figure>

<h2 id="H5软键盘缩回、弹起回调"><a href="#H5软键盘缩回、弹起回调" class="headerlink" title="H5软键盘缩回、弹起回调"></a>H5软键盘缩回、弹起回调</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/* 当软件键盘弹起会改变当前 window.innerHeight</span></span><br><span class="line"><span class="comment">监听这个值变化 [downCb 当软键盘弹起后，缩回的回调,upCb 当软键盘弹起的回调] */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span>(<span class="params">downCb, upCb</span>) </span>{ </span><br><span class="line">    <span class="keyword">var</span> clientHeight = <span class="built_in">window</span>.innerHeight</span><br><span class="line">    downCb = <span class="keyword">typeof</span> downCb === <span class="string">'function'</span> ? downCb : <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>{}</span><br><span class="line">    upCb = <span class="keyword">typeof</span> upCb === <span class="string">'function'</span> ? upCb : <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>{}</span><br><span class="line">    <span class="built_in">window</span>.addEventListener(<span class="string">'resize'</span>, <span class="function">() =&gt;</span> {</span><br><span class="line">        <span class="keyword">var</span> height = <span class="built_in">window</span>.innerHeight</span><br><span class="line">        <span class="keyword">if</span> (height === clientHeight) {</span><br><span class="line">            downCb()</span><br><span class="line">        }</span><br><span class="line">        <span class="keyword">if</span> (height &lt; clientHeight) {</span><br><span class="line">            upCb()</span><br><span class="line">        }</span><br><span class="line">    })</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="对象属性剔除"><a href="#对象属性剔除" class="headerlink" title="对象属性剔除"></a>对象属性剔除</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/** </span></span><br><span class="line"><span class="comment">* <span class="doctag">@param <span class="type">{object}</span> </span>object </span></span><br><span class="line"><span class="comment">* <span class="doctag">@param <span class="type">{string[]}</span> </span>props </span></span><br><span class="line"><span class="comment">* <span class="doctag">@return <span class="type">{object}</span> </span></span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">omit</span>(<span class="params">object, props=[]</span>)</span>{  </span><br><span class="line">    <span class="keyword">let</span> res = {}  </span><br><span class="line">    <span class="built_in">Object</span>.keys(object).forEach(<span class="function"><span class="params">key</span>=&gt;</span>{    </span><br><span class="line">        <span class="keyword">if</span>(props.includes(key) === <span class="literal">false</span>){      </span><br><span class="line">            res[key] = <span class="keyword">typeof</span> object[key] === <span class="string">'object'</span> &amp;&amp; object[key] !== <span class="literal">null</span> ? jsON.parse(jsON.stringify(object[key])) : object[key]    </span><br><span class="line">        }  </span><br><span class="line">    })         </span><br><span class="line">    <span class="keyword">return</span> res</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// for example</span></span><br><span class="line"><span class="keyword">let</span> data = {  <span class="attr">id</span>: <span class="number">1</span>,  <span class="attr">title</span>: <span class="string">'12345'</span>,  <span class="attr">name</span>: <span class="string">'男'</span>}</span><br><span class="line">omit(data, [<span class="string">'id'</span>]) </span><br><span class="line"><span class="comment">// data ---&gt; {title: 'xxx', name: '男'}</span></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></tbody></table></figure>

<h2 id="深拷贝"><a href="#深拷贝" class="headerlink" title="深拷贝"></a>深拷贝</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * This is just a simple version of deep copy</span></span><br><span class="line"><span class="comment"> * Has a lot of edge cases bug</span></span><br><span class="line"><span class="comment"> * If you want to use a perfect deep copy, use lodash's _.cloneDeep</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Object}</span> <span class="variable">source</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{Object}</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">deepClone</span>(<span class="params">source</span>) </span>{</span><br><span class="line">    <span class="keyword">if</span> (!source &amp;&amp; <span class="keyword">typeof</span> source !== <span class="string">'object'</span>) {</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'error arguments'</span>, <span class="string">'deepClone'</span>)</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">const</span> targetObj = source.constructor === <span class="built_in">Array</span> ? [] : {}</span><br><span class="line">    <span class="built_in">Object</span>.keys(source).forEach(<span class="function"><span class="params">keys</span> =&gt;</span> {</span><br><span class="line">        <span class="keyword">if</span> (source[keys] &amp;&amp; <span class="keyword">typeof</span> source[keys] === <span class="string">'object'</span>) {</span><br><span class="line">            targetObj[keys] = deepClone(source[keys])</span><br><span class="line">        } <span class="keyword">else</span> {</span><br><span class="line">            targetObj[keys] = source[keys]</span><br><span class="line">        }</span><br><span class="line">    })</span><br><span class="line">    <span class="keyword">return</span> targetObj</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="函数防抖"><a href="#函数防抖" class="headerlink" title="函数防抖"></a>函数防抖</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">func, wait, immediate</span>) </span>{</span><br><span class="line">    <span class="keyword">let</span> timeout, args, context, timestamp, result</span><br><span class="line">    <span class="keyword">const</span> later = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>{</span><br><span class="line">        <span class="comment">// 据上一次触发时间间隔</span></span><br><span class="line">        <span class="keyword">const</span> last = +<span class="keyword">new</span> <span class="built_in">Date</span>() - timestamp</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait</span></span><br><span class="line">        <span class="keyword">if</span> (last &lt; wait &amp;&amp; last &gt; <span class="number">0</span>) {</span><br><span class="line">            timeout = <span class="built_in">setTimeout</span>(later, wait - last)</span><br><span class="line">        } <span class="keyword">else</span> {</span><br><span class="line">            timeout = <span class="literal">null</span></span><br><span class="line">            <span class="comment">// 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用</span></span><br><span class="line">            <span class="keyword">if</span> (!immediate) {</span><br><span class="line">                result = func.apply(context, args)</span><br><span class="line">                <span class="keyword">if</span> (!timeout) context = args = <span class="literal">null</span></span><br><span class="line">            }</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>{</span><br><span class="line">        context = <span class="built_in">this</span></span><br><span class="line">        timestamp = +<span class="keyword">new</span> <span class="built_in">Date</span>()</span><br><span class="line">        <span class="keyword">const</span> callNow = immediate &amp;&amp; !timeout</span><br><span class="line">        <span class="comment">// 如果延时不存在，重新设定延时</span></span><br><span class="line">        <span class="keyword">if</span> (!timeout) timeout = <span class="built_in">setTimeout</span>(later, wait)</span><br><span class="line">        <span class="keyword">if</span> (callNow) {</span><br><span class="line">            result = func.apply(context, args)</span><br><span class="line">            context = args = <span class="literal">null</span></span><br><span class="line">        }</span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<h2 id="函数节流"><a href="#函数节流" class="headerlink" title="函数节流"></a>函数节流</h2><figure class="highlight js"><table><tbody><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Function}</span> </span>func 目标函数</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Number}</span> </span>wait  延迟执行毫秒数</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Number}</span> </span>type  type 1 表时间戳版，2 表定时器版</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span>(<span class="params">func, wait ,type</span>) </span>{ </span><br><span class="line">    <span class="keyword">if</span>(type===<span class="number">1</span>){</span><br><span class="line">        <span class="keyword">let</span> previous = <span class="number">0</span>;</span><br><span class="line">    }<span class="keyword">else</span> <span class="keyword">if</span>(type===<span class="number">2</span>){</span><br><span class="line">        <span class="keyword">let</span> timeout;</span><br><span class="line">    }</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>{</span><br><span class="line">        <span class="keyword">let</span> context = <span class="built_in">this</span>;</span><br><span class="line">        <span class="keyword">let</span> args = <span class="built_in">arguments</span>;</span><br><span class="line">        <span class="keyword">if</span>(type===<span class="number">1</span>){</span><br><span class="line">            <span class="keyword">let</span> now = <span class="built_in">Date</span>.now();</span><br><span class="line">            <span class="keyword">if</span> (now - previous &gt; wait) {</span><br><span class="line">                func.apply(context, args);</span><br><span class="line">                previous = now;</span><br><span class="line">            }</span><br><span class="line">        }<span class="keyword">else</span> <span class="keyword">if</span>(type===<span class="number">2</span>){</span><br><span class="line">            <span class="keyword">if</span> (!timeout) {</span><br><span class="line">                timeout = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> {</span><br><span class="line">                    timeout = <span class="literal">null</span>;</span><br><span class="line">                    func.apply(context, args)</span><br><span class="line">                }, wait)</span><br><span class="line">            }</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure>

<p>推荐阅读</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://htmldom.dev/">Manage HTML DOM</a></li>
<li><a target="_blank" rel="noopener" href="https://csslayout.io/">CSS Layout</a></li>
<li><a target="_blank" rel="noopener" href="https://1loc.dev/">Favorite JavaScript Utilities</a></li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://fe32.top">Ethan.Tzy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://fe32.top/articles/ut0927il/">https://fe32.top/articles/ut0927il/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://fe32.top" target="_blank">唐志远の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/@3.7.1/tags/JavaScript/">JavaScript</a><a class="post-meta__tags" href="/@3.7.1/tags/%E5%B7%A5%E5%85%B7%E5%87%BD%E6%95%B0/">工具函数</a></div><div class="post_share"><div class="social-share" data-image="https://bu.dusays.com/2022/05/01/626e921f1090a.png" data-sites="facebook,twitter,google,wechat,weibo,qq"></div><link rel="stylesheet" href="https://npm.elemecdn.com/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://bu.dusays.com/2022/05/17/6283c3f127558.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://bu.dusays.com/2022/05/17/6283c3f127558.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://bu.dusays.com/2022/05/17/6283c3ee6d872.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://bu.dusays.com/2022/05/17/6283c3ee6d872.jpg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/@3.7.1/articles/np2021sm/"><img class="prev-cover" data-lazy-src="https://bu.dusays.com/2022/05/01/626e91194b2bb.png" onerror="onerror=null;src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">CSS 实现新拟态(Neumorphism) UI 风格</div></div></a></div><div class="next-post pull-right"><a href="/@3.7.1/articles/ele265ui/"><img class="next-cover" data-lazy-src="https://bu.dusays.com/2022/05/01/626e8e70b3308.png" onerror="onerror=null;src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">记录关于Vue+element-Ui的系列问题</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/@3.7.1/articles/jsnb9527/" title="JavaScript 核心进阶"><img class="cover" data-lazy-src="https://bu.dusays.com/2022/06/09/62a0e411ed838.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-09</div><div class="title">JavaScript 核心进阶</div></div></a></div><div><a href="/@3.7.1/articles/jsnb9529/" title="前端基础进阶（二）：执行上下文详细图解"><img class="cover" data-lazy-src="https://bu.dusays.com/2022/06/12/62a5cb5aa2fe2.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-12</div><div class="title">前端基础进阶（二）：执行上下文详细图解</div></div></a></div><div><a href="/@3.7.1/articles/jsnb9528/" title="前端基础进阶（一）：内存空间详细图解"><img class="cover" data-lazy-src="https://bu.dusays.com/2022/06/10/62a229f378f16.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-10</div><div class="title">前端基础进阶（一）：内存空间详细图解</div></div></a></div><div><a href="/@3.7.1/articles/jsnb9530/" title="前端基础进阶（三）：变量对象详解"><img class="cover" data-lazy-src="https://bu.dusays.com/2022/06/12/62a5de91bc968.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-12</div><div class="title">前端基础进阶（三）：变量对象详解</div></div></a></div><div><a href="/@3.7.1/articles/jsnb9531/" title="前端基础进阶（四）：作用域与作用域链"><img class="cover" data-lazy-src="https://bu.dusays.com/2022/06/12/62a5fe9aaff7a.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-12</div><div class="title">前端基础进阶（四）：作用域与作用域链</div></div></a></div><div><a href="/@3.7.1/articles/jsnb9532/" title="前端基础进阶（五）：闭包"><img class="cover" data-lazy-src="https://bu.dusays.com/2022/06/13/62a742049639e.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-13</div><div class="title">前端基础进阶（五）：闭包</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" onerror="this.onerror=null;this.src='https://bu.dusays.com/2021/03/27/0106da541a922.gif'" alt="avatar"/><div class="author-info__name">Ethan.Tzy</div><div class="author-info__description">2023年的理想开始实现了吗？</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/@3.7.1/archives/"><div class="headline">文章</div><div class="length-num">101</div></a></div><div class="card-info-data-item is-center"><a href="/@3.7.1/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div><div class="card-info-data-item is-center"><a href="/@3.7.1/categories/"><div class="headline">分类</div><div class="length-num">20</div></a></div></div><div class="card-info-social-icons is-center"><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2938526863&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://bu.dusays.com/2022/05/17/6283c39fcfc2f.png" target="_blank" title="Wechat"><i class="fab fa-weixin"></i></a><a class="social-icon" href="mailto:ethan4116@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://github.com/tzy13755126023" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="/@3.7.1/atom.xml" target="_blank" title="Rss"><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content"><div style='text-indent:2em'>本站只保留入口，即将不再更新内容，请切换成回最新版本。</div><div id="qq-btn"><a id="a-qun" href="https://fe32.top/" target="_blank">回最新版本 ✨</a></div><div id="qq-btn" style="margin-top:10px"><a id="a-qun" href="https://qm.qq.com/cgi-bin/qm/qr?k=IqfyAyFpCIMln6xPXkjkI_gzF8zx29zK&jump_from=webapi&authKey=jcME5f+e8XES0vAaUTAaI24tsgUMdoIZ0oGwAOoHNpK1HSWdcI9zmSlWVdfw/ax+" target="_blank">加入QQ群 ✨</a></div></div></div><div class="card-widget tzy-right-widget" id="card-wechat"><div id="flip-wrapper"><div id="flip-content"><div class="face"></div><div class="back face"></div></div></div></div><div class="xpand" style="height:200px;"><canvas class="illo" width="800" height="800" style="max-width: 200px; max-height: 200px; touch-action: none; width: 640px; height: 640px;"></canvas></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A0%BC%E5%BC%8F%E5%8C%96%E6%97%B6%E9%97%B4%E6%88%B3"><span class="toc-number">2.</span> <span class="toc-text">格式化时间戳</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%97%B6%E9%97%B4%E6%A0%BC%E5%BC%8F%E5%8C%96-%E5%87%A0%E5%88%86%E9%92%9F%E5%89%8D-%E5%87%A0%E5%B0%8F%E6%97%B6%E5%89%8D"><span class="toc-number">3.</span> <span class="toc-text">时间格式化 几分钟前 几小时前</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#url%E5%8F%82%E6%95%B0%E8%BD%AC%E4%B8%BA%E5%AF%B9%E8%B1%A1"><span class="toc-number">4.</span> <span class="toc-text">url参数转为对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E5%BA%8F%E5%88%97%E5%8C%96%E3%80%90%E5%AF%B9%E8%B1%A1%E8%BD%ACurl%E5%8F%82%E6%95%B0%E3%80%91"><span class="toc-number">5.</span> <span class="toc-text">对象序列化【对象转url参数】</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9C%AC%E5%9C%B0%E5%AD%98%E5%82%A8"><span class="toc-number">6.</span> <span class="toc-text">本地存储</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#cookie%E6%93%8D%E4%BD%9C"><span class="toc-number">7.</span> <span class="toc-text">cookie操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E5%AD%97%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%8D%95%E4%BD%8D"><span class="toc-number">8.</span> <span class="toc-text">数字格式化单位</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E5%AD%97%E5%8D%83%E4%BD%8D%E8%BF%87%E6%BB%A4"><span class="toc-number">9.</span> <span class="toc-text">数字千位过滤</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%87%E6%BB%A4%E6%88%90%E7%89%88%E6%9C%AC%E5%8F%B7"><span class="toc-number">10.</span> <span class="toc-text">过滤成版本号</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A6%96%E5%AD%97%E6%AF%8D%E5%A4%A7%E5%86%99"><span class="toc-number">11.</span> <span class="toc-text">首字母大写</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#class%E9%AA%9A%E6%93%8D%E4%BD%9C"><span class="toc-number">12.</span> <span class="toc-text">class骚操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E6%9C%AC%E5%A4%8D%E5%88%B6%E5%8A%9F%E8%83%BD"><span class="toc-number">13.</span> <span class="toc-text">文本复制功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E6%98%AF%E4%B8%80%E4%B8%AA%E6%95%B0%E7%BB%84"><span class="toc-number">14.</span> <span class="toc-text">判断是否是一个数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E6%98%AF%E4%B8%80%E4%B8%AA%E7%A9%BA%E6%95%B0%E7%BB%84"><span class="toc-number">15.</span> <span class="toc-text">判断是否是一个空数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%8B%E9%9A%86%E4%B8%80%E4%B8%AA%E6%95%B0%E7%BB%84"><span class="toc-number">16.</span> <span class="toc-text">克隆一个数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D"><span class="toc-number">17.</span> <span class="toc-text">数组去重</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%98%AF%E5%90%A6%E4%B8%BAPC%E7%AB%AF"><span class="toc-number">18.</span> <span class="toc-text">是否为PC端</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E4%B8%BA%E5%BE%AE%E4%BF%A1"><span class="toc-number">19.</span> <span class="toc-text">判断是否为微信</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%BE%E5%A4%87%E5%88%A4%E6%96%AD%EF%BC%9Aandroid%E3%80%81ios%E3%80%81web"><span class="toc-number">20.</span> <span class="toc-text">设备判断：android、ios、web</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%B8%E8%A7%81%E6%AD%A3%E5%88%99%E6%A0%A1%E9%AA%8C"><span class="toc-number">21.</span> <span class="toc-text">常见正则校验</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8E%BB%E9%99%A4%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%A9%BA%E6%A0%BC"><span class="toc-number">22.</span> <span class="toc-text">去除字符串空格</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%87%E6%BB%A4html%E4%BB%A3%E7%A0%81"><span class="toc-number">23.</span> <span class="toc-text">过滤html代码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%9F%E6%88%90%E9%9A%8F%E6%9C%BA%E6%95%B0%E8%8C%83%E5%9B%B4"><span class="toc-number">24.</span> <span class="toc-text">生成随机数范围</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A4%E6%96%AD%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%AE%8C%E6%88%90"><span class="toc-number">25.</span> <span class="toc-text">判断图片加载完成</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%89%E6%A0%87%E6%89%80%E5%9C%A8%E4%BD%8D%E7%BD%AE%E6%8F%92%E5%85%A5%E5%AD%97%E7%AC%A6"><span class="toc-number">26.</span> <span class="toc-text">光标所在位置插入字符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%BE%E7%89%87%E5%9C%B0%E5%9D%80%E8%BD%ACbase64"><span class="toc-number">27.</span> <span class="toc-text">图片地址转base64</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#base64%E5%9B%BE%E7%89%87%E4%B8%8B%E8%BD%BD%E5%8A%9F%E8%83%BD"><span class="toc-number">28.</span> <span class="toc-text">base64图片下载功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E6%98%AF%E5%90%A6%E6%94%AF%E6%8C%81webP%E6%A0%BC%E5%BC%8F%E5%9B%BE%E7%89%87"><span class="toc-number">29.</span> <span class="toc-text">浏览器是否支持webP格式图片</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#H5%E8%BD%AF%E9%94%AE%E7%9B%98%E7%BC%A9%E5%9B%9E%E3%80%81%E5%BC%B9%E8%B5%B7%E5%9B%9E%E8%B0%83"><span class="toc-number">30.</span> <span class="toc-text">H5软键盘缩回、弹起回调</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E5%B1%9E%E6%80%A7%E5%89%94%E9%99%A4"><span class="toc-number">31.</span> <span class="toc-text">对象属性剔除</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B7%B1%E6%8B%B7%E8%B4%9D"><span class="toc-number">32.</span> <span class="toc-text">深拷贝</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E9%98%B2%E6%8A%96"><span class="toc-number">33.</span> <span class="toc-text">函数防抖</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E8%8A%82%E6%B5%81"><span class="toc-number">34.</span> <span class="toc-text">函数节流</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/joy10001/" title="被发现了，这些吊炸天的摸鱼网站！"><img data-lazy-src="https://bu.dusays.com/2023/06/18/648f1359dc90f.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="被发现了，这些吊炸天的摸鱼网站！"/></a><div class="content"><a class="title" href="/@3.7.1/articles/joy10001/" title="被发现了，这些吊炸天的摸鱼网站！">被发现了，这些吊炸天的摸鱼网站！</a><time datetime="2023-06-18T16:40:07.000Z" title="发表于 2023-06-19 00:40:07">2023-06-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/vue20002/" title="解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题"><img data-lazy-src="https://bu.dusays.com/2023/06/18/648ed3f987511.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题"/></a><div class="content"><a class="title" href="/@3.7.1/articles/vue20002/" title="解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题">解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题</a><time datetime="2023-06-18T16:20:32.000Z" title="发表于 2023-06-19 00:20:32">2023-06-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/hexo1619/" title="如何新窗口打开导航链接？"><img data-lazy-src="https://bu.dusays.com/2023/06/04/647c9bb365e09.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="如何新窗口打开导航链接？"/></a><div class="content"><a class="title" href="/@3.7.1/articles/hexo1619/" title="如何新窗口打开导航链接？">如何新窗口打开导航链接？</a><time datetime="2023-06-04T13:53:07.000Z" title="发表于 2023-06-04 21:53:07">2023-06-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/ts30001/" title="一文读懂TS的(.d.ts)文件"><img data-lazy-src="https://bu.dusays.com/2023/04/29/644d384035bca.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="一文读懂TS的(.d.ts)文件"/></a><div class="content"><a class="title" href="/@3.7.1/articles/ts30001/" title="一文读懂TS的(.d.ts)文件">一文读懂TS的(.d.ts)文件</a><time datetime="2023-04-30T14:28:06.000Z" title="发表于 2023-04-30 22:28:06">2023-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/vue20001/" title="Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法"><img data-lazy-src="https://bu.dusays.com/2023/04/29/644d249bc9001.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法"/></a><div class="content"><a class="title" href="/@3.7.1/articles/vue20001/" title="Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法">Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法</a><time datetime="2023-04-30T12:34:18.000Z" title="发表于 2023-04-30 20:34:18">2023-04-30</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://bu.dusays.com/2021/12/31/5667b38b6bad0.jpg')"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">公益广告</p><div class="bg-ad"><div>国家反诈中心是国务院打击治理电信网络新型违法犯罪工作部际联席会议合成作战平台，集资源整合、情报研判、侦查指挥为一体，在打击、防范、治理电信网络诈骗等新型违法犯罪中发挥着重要作用。</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://www.hack-gov.com.cn/posts/21480.html">下载（国家反诈中心） APP</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">修仙导航</p><ul class="ft-links"><li><a target="_blank" rel="noopener" href="https://tzy1997.com/articles/hexo1600/">建站指南</a><a target="_blank" rel="noopener" href="https://tzy1997.com/nav.html">网址导航</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/sponsorWall/">来杯咖啡</a><a target="_blank" rel="noopener" href="https://tzy1997.com/comments/">留点什么</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/about/">关于博主</a><a target="_blank" rel="noopener" href="https://tzy1997.com/archives/">文章归档</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/categories/">文章分类</a><a target="_blank" rel="noopener" href="https://tzy1997.com/tags/">文章标签</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/gallery/">我的相册</a><a target="_blank" rel="noopener" href="https://tzy1997.com/bangumis/">我的追番</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/specialEffects/">一些特效</a><a target="_blank" rel="noopener" href="https://tzy1997.com/wallpaper/">一些壁纸</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链</p><div class="ft-img-group"><div class="img-group-item"><a target="_blank" rel="noopener" href="https://tzy1997.com/"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://blog.zhheo.com/"><img src="https://npm.elemecdn.com/guli-heo/img/avatar2.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.thyuu.com/"><img src="https://npm.elemecdn.com/imgscdn/img/202111191951780.JPG" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://dusays.com/"><img src="https://cdn.dusays.com/avatar.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://akilar.top/"><img src="https://npm.elemecdn.com/akilar-candyassets/image/siteicon/favicon.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.fomal.cc/"><img src="https://bu.dusays.com/2022/11/06/6367af8667f0e.webp" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.startly.cn/"><img src="https://bu.dusays.com/2023/04/15/643a99cb740a4.jpg" alt=""/></a></div><div class="img-group-item"><a href="javascript:btf.snackbarShow(&quot;预留友链位~~&quot;)"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" alt=""/></a></div></div></div></div><div class="copyright">&copy;2020 - 2023  <i id="heartbeat" class="fa fas fa-heartbeat"></i> Ethan.Tzy</div><div class="footer_custom_text">I wish you to become your own sun, no need to rely on who's light.✨✨✨<p><a target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a>&nbsp;<a target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a>&nbsp;<a target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a> &nbsp;<a target="_blank" href="https://vercel.com/ "><img src="https://img.shields.io/badge/Hosted-Vervel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a>&nbsp;<a target="_blank" href="https://icp.gov.moe/?keyword=20220686" title="本站已加入萌ICP豪华套餐，萌ICP备20220686号"><img src="https://img.shields.io/badge/%E8%90%8CICP%E5%A4%87-20220686-fe1384?style-flat&amp;logo="></a>&nbsp;<a target="_blank" href="https://vercel.com/"><img src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a>&nbsp;<a target="_blank" href="https://github.com/"><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a>&nbsp;<a target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="在线聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuPlugin"><div class="rightMenu-item" id="menu-copytext"><i class="fa-solid fa-copy"></i><span>复制文本</span></div><div class="rightMenu-item" id="menu-newwindow"><i class="fa-solid fa-window-restore"></i><span>新窗口打开</span></div><div class="rightMenu-item" id="menu-copylink"><i class="fa-solid fa-copy"></i><span>复制链接地址</span></div><div class="rightMenu-item" id="menu-copyimg"><i class="fa-solid fa-copy"></i><span>复制图片</span></div><div class="rightMenu-item" id="menu-downloadimg"><i class="fa-solid fa-download"></i><span>下载图片</span></div><div class="rightMenu-item" id="menu-search"><i class="fa-solid fa-magnifying-glass"></i><span>站内搜索</span></div><div class="rightMenu-item" id="menu-searchBaidu"><i class="fa-solid fa-magnifying-glass"></i><span>百度搜索</span></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><div class="rightMenu-item" id="menu-radompage"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></div><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a><a class="rightMenu-item" id="menu-goto-comment" href="#post-comment"><i class="fas fa-comment"></i><span>空降评论</span></a><a class="rightMenu-item menu-link" href="/sponsorWall/"><i class="fa-solid fa-money-check-alt"></i><span>赞助墙</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-readmode"><i class="fa-solid fa-book-open"></i><span>阅读模式</span></div><div class="rightMenu-item" id="menu-print"><i class="fa-solid fa-print fa-fw"></i><span>打印页面</span></div><div class="rightMenu-item" id="menu-copy"><i class="fa-solid fa-share"></i><span>分享本页</span></div></div></div><div id="rightmenu-mask"></div><div id="myscoll"></div><div><script src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script src="/@3.7.1/"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/utils.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/main.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/tw_cn.js"></script><script src="https://npm.elemecdn.com/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/search/algolia.js"></script><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())
setTimeout(function(){preloader.endLoading();}, 5000);</script><div class="js-pjax"><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo.fe32.top/',
      region: '',
      onCommentLoaded: function () {
        //- const ele = document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)')
      }
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'https://twikoo.fe32.top/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://fastly.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'https://twikoo.fe32.top/',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://fastly.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (true) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><div class="pjax-reload"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '1s');
    arr[i].setAttribute('data-wow-delay', '1s');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('site-card');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__flipInY');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '100ms');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('github-badge');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__flipInX');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '100ms');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer="defer" src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/wow.min.js"></script><script defer="defer" src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/wow_init.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/cat.js"></script><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/issues.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/twopeople1.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/zdog.dist.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/twopeople.js"></script><canvas id="universe"></canvas><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/universe.js"></script><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/ethan_tzy.js"></script><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/right-menu/rightMenu@3.7.1.js"></script><script async src="//at.alicdn.com/t/font_2315348_g8vs01iykv.js"></script><script async src="https://www.googletagmanager.com/gtag/js?id=G-92YZLM7C2B"></script><script> window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', 'G-92YZLM7C2B');</script><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9697737937582017" crossorigin="anonymous"></script><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "https://hm.baidu.com/hm.js?bbcbaf179f87d03d28c3ba72c79a5640";var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s);})();</script><script>!function(p){"use strict";!function(t){var s=window,e=document,i=p,c="".concat("https:"===e.location.protocol?"https://":"http://","sdk.51.la/js-sdk-pro.min.js"),n=e.createElement("script"),r=e.getElementsByTagName("script")[0];n.type="text/javascript",n.setAttribute("charset","UTF-8"),n.async=!0,n.src=c,n.id="LA_COLLECT",i.d=n;var o=function(){s.LA.ids.push(i)};s.LA?s.LA.ids&&o():(s.LA=p,s.LA.ids=[],o()),r.parentNode.insertBefore(n,r)}()}({id:"Jo9JJAc5cBaxwwnJ",ck:"Jo9JJAc5cBaxwwnJ"});</script><script src="https://npm.elemecdn.com/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://npm.elemecdn.com/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script>window.$crisp = [];
window.CRISP_WEBSITE_ID = "58b8ce9e-19e0-46ff-8e8d-6ee1b1b25c45";
(function () {
  d = document;
  s = d.createElement("script");
  s.src = "https://client.crisp.chat/l.js";
  s.async = 1;
  d.getElementsByTagName("head")[0].appendChild(s);
})();
$crisp.push(["safe", true])

if (true) {
  $crisp.push(["do", "chat:hide"])
  $crisp.push(["on", "chat:closed", function() {
    $crisp.push(["do", "chat:hide"])
  }])
  var chatBtnFn = () => {
    var chatBtn = document.getElementById("chat_btn")
    chatBtn.addEventListener("click", function(){
      $crisp.push(["do", "chat:show"])
      $crisp.push(["do", "chat:open"])

    });
  }
  chatBtnFn()
} else {
  if (false) {
    function chatBtnHide () {
      $crisp.push(["do", "chat:hide"])
    }
    function chatBtnShow () {
      $crisp.push(["do", "chat:show"])
    }
  }
}</script><link rel="stylesheet" href="https://npm.elemecdn.com/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/aplayer/dist/APlayer.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/meting.min.js"></script><script src="https://npm.elemecdn.com/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener toc scroll 
  window.removeEventListener('scroll', window.tocScrollFn)

  typeof preloader === 'object' && preloader.initLoading()

  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  //- document.querySelectorAll('script[data-pjax]').forEach(item => {
  
  document.querySelectorAll('script[data-pjax], .pjax-reload script').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})


//- document.addEventListener('pjax:send', function () {
//-   typeof preloader === 'object' && preloader.initLoading()
  
//-   if (window.aplayers) {
//-     for (let i = 0; i < window.aplayers.length; i++) {
//-       if (!window.aplayers[i].options.fixed) {
//-         window.aplayers[i].destroy()
//-       }
//-     }
//-   }

//-   typeof typed === 'object' && typed.destroy()

//-   //reset readmode
//-   const $bodyClassList = document.body.classList
//-   $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

//- })

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    if (false) {
      location.hash && e.request.responseURL !== location.href ? pjax.loadUrl(location.href) : pjax.loadUrl('/404.html')
      return
    }
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>